package cn.shengchao.examstar.knowledge.acl.adapters;

import cn.shengchao.examstar.knowledge.acl.dto.KnowledgePointMasteryDTO;
import cn.shengchao.examstar.knowledge.acl.ports.KnowledgePointMasteryPort;
import cn.shengchao.examstar.knowledge.domain.entity.KnowledgePointMastery;
import cn.shengchao.examstar.knowledge.domain.service.KnowledgePointMasteryService;
import cn.shengchao.examstar.knowledge.domain.vo.MasteryStatusEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 知识点掌握度接口实现
 * 实现ACL端口，与领域服务进行集成
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class KnowledgePointMasteryPortImpl implements KnowledgePointMasteryPort {

    private final KnowledgePointMasteryService masteryService;

    @Override
    public KnowledgePointMasteryDTO updateKnowledgePointMastery(Long userId, Long knowledgePointId,
                                                          String degreeOfMastery, String accuracyRate,
                                                          Long studyPlanId) {
        log.info("ACL层更新知识点掌握度: 用户ID={}, 知识点ID={}, 掌握度={}, 正确率={}, 学习计划ID={}",
                userId, knowledgePointId, degreeOfMastery, accuracyRate, studyPlanId);

        // 调用领域服务更新掌握度
        KnowledgePointMastery mastery = masteryService.updateMastery(
                userId, knowledgePointId, degreeOfMastery, accuracyRate, studyPlanId);

        // 转换为DTO
        return convertToDto(mastery);
    }

    @Override
    public List<KnowledgePointMasteryDTO> batchUpdateMastery(List<KnowledgePointMasteryDTO> knowledgePointMasteryList) {
        if (knowledgePointMasteryList == null || knowledgePointMasteryList.isEmpty()) {
            return new ArrayList<>();
        }

        log.info("ACL层批量更新知识点掌握度: 数量={}", knowledgePointMasteryList.size());

        // 转换为领域实体
        List<KnowledgePointMastery> masteryEntities = knowledgePointMasteryList.stream()
                .map(this::convertToEntity)
                .collect(Collectors.toList());

        // 批量更新
        masteryService.batchUpdateMastery(masteryEntities);

        // 重新查询更新后的结果
        // 这里简化处理，直接返回转换后的DTO列表
        return masteryEntities.stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }

    @Override
    public List<KnowledgePointMasteryDTO> getStudyPlanKnowledgePointMasteries(Long studyPlanId) {
        log.info("ACL层查询学习计划知识点掌握度: 学习计划ID={}", studyPlanId);

        // 调用领域服务查询掌握度
        List<KnowledgePointMastery> masteryList = masteryService.getMasteriesByStudyPlan(studyPlanId);

        // 转换为DTO列表
        return masteryList.stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }
    
    @Override
    public KnowledgePointMasteryDTO updateKnowledgePointMasteryStatus(Long userId, Long knowledgePointId, 
                                                                       MasteryStatusEnum status) {
        log.info("ACL层更新知识点掌握度状态: 用户ID={}, 知识点ID={}, 状态={}",
                userId, knowledgePointId, status);
        
        // 调用领域服务更新掌握度状态
        KnowledgePointMastery mastery = masteryService.updateMasteryStatus(userId, knowledgePointId, status);
        
        // 转换为DTO
        return convertToDto(mastery);
    }
    
    @Override
    public List<KnowledgePointMasteryDTO> batchUpdateKnowledgePointMasteryStatus(Long userId, List<Long> knowledgePointIds, 
                                                                                MasteryStatusEnum status) {
        log.info("ACL层批量更新知识点掌握度状态: 用户ID={}, 知识点数量={}, 状态={}",
                userId, knowledgePointIds.size(), status);
        
        // 调用领域服务批量更新掌握度状态
        masteryService.batchUpdateMasteryStatus(userId, knowledgePointIds, status);
        
        // 获取更新后的掌握度列表
        List<KnowledgePointMastery> masteryList = new ArrayList<>();
        for (Long knowledgePointId : knowledgePointIds) {
            masteryService.getMasteryByUserAndKnowledgePoint(userId, knowledgePointId)
                .ifPresent(masteryList::add);
        }
        
        // 转换为DTO列表
        return masteryList.stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }

    /**
     * 将领域实体转换为DTO
     */
    private KnowledgePointMasteryDTO convertToDto(KnowledgePointMastery entity) {
        if (entity == null) {
            return null;
        }

        return KnowledgePointMasteryDTO.builder()
                .id(entity.getId())
                .userId(entity.getUserId())
                .knowledgePointId(entity.getKnowledgePointId())
                .degreeOfMastery(entity.getDegreeOfMastery())
                .accuracyRate(entity.getAccuracyRate())
                .studyPlanId(entity.getStudyPlanId())
                .status(entity.getStatus())
                .build();
    }

    /**
     * 将DTO转换为领域实体
     */
    private KnowledgePointMastery convertToEntity(KnowledgePointMasteryDTO dto) {
        if (dto == null) {
            return null;
        }

        return KnowledgePointMastery.builder()
                .id(dto.getId())
                .userId(dto.getUserId())
                .knowledgePointId(dto.getKnowledgePointId())
                .degreeOfMastery(dto.getDegreeOfMastery())
                .accuracyRate(dto.getAccuracyRate())
                .studyPlanId(dto.getStudyPlanId())
                .status(dto.getStatus() != null ? dto.getStatus() : MasteryStatusEnum.NEW.getCode()) // 使用枚举：默认状态为新建
                .build();
    }
} 